package com.smile.commons;

import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.util.SaResult;
import com.smile.commons.page.R;
import com.smile.commons.request.RequestIdUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public R<Object> handleException(Exception e) {
        log.error(e.getMessage(), e);
        R<Object> fail = R.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
        fail.setRequestId(RequestIdUtils.get());
        return fail;
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R<Object> validateException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String, Object> map = new HashMap<>();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        FieldError fieldError = fieldErrors.get(0);
        map.put("field", fieldError.getField());
        map.put("msg", fieldError.getDefaultMessage());
        R<Object> fail = R.fail("数据校验异常," + map);
        fail.setRequestId(RequestIdUtils.get());
        return fail;

    }

    @ExceptionHandler(SaTokenException.class)
    public SaResult handlerSaTokenException(SaTokenException e) {

        // 根据不同异常细分状态码返回不同的提示

        if (e.getCode() == 11011) {
            return new SaResult(401, "token已失效，请重新登录", "");
        }

//        if (e.getCode() == 30005) {
//            return new SaResult(401,"内部服务器错误","");
//        }
//
//        if (e.getCode() == 30006) {
//            return new SaResult(401,"内部服务器错误","");
//        }

//        if (e.getCode() == 30006) {
////            return new SaResult(401,"token已失效，请重新登录","");
//        }

        if (e.getCode() == 11011) {
            return new SaResult(401, "token已失效，请重新登录", "");
        }

        if (e.getCode() == 11012) {
            return new SaResult(401, "token已失效，请重新登录", "");
//            return SaResult.error("redirect 重定向 url 不在 allowUrl 允许的范围内");
        }
        if (e.getCode() == 11013) {
            return new SaResult(401, "token已失效，请重新登录", "");
        }
        // 更多 code 码判断 ...

        // 默认的提示
        return new SaResult(401, "token已失效，请重新登录", "");
    }

}
